import { ForbiddenException, Injectable } from '@nestjs/common';
import { VideoItem, VideoItemUser } from './video-item.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Video } from '../video/video.entity';

@Injectable()
export class VideoItemService {
  constructor(
    @InjectRepository(Video) private video: Repository<Video>,
    @InjectRepository(VideoItem) private videoItem: Repository<VideoItem>,
    @InjectRepository(VideoItemUser)
    private videoItemUser: Repository<VideoItemUser>,
  ) {}

  // 查询视频itemm列表
  async getVideoItemList(params) {
    if (!params.id)
      throw new ForbiddenException({
        message: '视频id不能为空!',
        code: 1,
      });
    const videoItemList: any = await this.videoItem
      .createQueryBuilder('video')
      .where({ videoId: params.id })
      .getMany();
    return videoItemList;
  }

  //  创建视频item
  async addVideoItem(bodyData) {
    const { videoId, videoUrl, videoNumber } = bodyData;
    if (!videoId)
      throw new ForbiddenException({
        message: '视频videoId不能为空!',
        code: 1,
      });
    if (!videoUrl)
      throw new ForbiddenException({
        message: '视频链接videoUrl不能为空!',
        code: 1,
      });
    const categoryResult = await this.video.findOne({
      where: { id: videoId },
    });
    if (!categoryResult)
      throw new ForbiddenException({ message: '该视频不存在!', code: 1 });
    try {
      await this.videoItem.save({
        videoId,
        videoUrl,
        videoNumber,
        create_time: new Date(),
        updated_time: new Date(),
      });
      return [];
    } catch (e) {
      console.log('error:', e);
      throw new ForbiddenException({ message: e, code: 1 });
    }
  }

  // 修改视频item
  editVideoItem(bodyData) {
    const { id, videoId, videoUrl, videoNumber } = bodyData;
    if (!id)
      throw new ForbiddenException({
        message: '视频item ID不能为空!',
        code: 1,
      });
    if (!videoId)
      throw new ForbiddenException({
        message: '视频videoId不能为空!',
        code: 1,
      });
    if (!videoUrl)
      throw new ForbiddenException({
        message: '视频链接videoUrl不能为空!',
        code: 1,
      });
    try {
      this.videoItem.update(id, {
        videoId,
        videoUrl,
        videoNumber,
        updated_time: new Date(),
      });
    } catch (e) {
      console.log('error:', e);
      throw new ForbiddenException({
        message: 'e!',
        code: 1,
      });
    }
  }

  //  删除视频item
  deleteVideoItem(params) {
    if (!params.id)
      throw new ForbiddenException({
        message: '视频item ID不能为空!',
        code: 1,
      });
    try {
      this.videoItem.delete({ id: params.id });
      return [];
    } catch (e) {
      console.log('error:', e);
      throw new ForbiddenException({ message: e, code: 1 });
    }
  }

  // 获取历史记录
  getHistoryList(params) {
    return this.videoItemUser
      .createQueryBuilder('videoItemUser')
      .where({ userId: params.userId })
      .getMany();
  }

  // 获取单个历史记录
  getHistoryOne(params) {
    if (!params.videoId)
      throw new ForbiddenException({
        message: '视频ID videoId 不能为空!',
        code: 1,
      });
    return this.videoItemUser
      .createQueryBuilder('videoItemUser')
      .where({ userId: params.userId })
      .andWhere({ videoId: params.videoId })
      .orderBy('updated_time', 'DESC')
      .getMany();
  }

  // 添加用户观看记录
  async addHistory(bodyData) {
    const { videoItemId, historyRecord, userId,videoId } = bodyData;
    if (!videoItemId)
      throw new ForbiddenException({
        message: '视频item-ID videoItemId 不存在!',
        code: 1,
      });
    if (!historyRecord)
      throw new ForbiddenException({
        message: '视频历史 historyRecord 不存在!',
        code: 1,
      });
    const categoryResult = await this.videoItem.findOne({
      where: { id: videoItemId },
    });
    if (!categoryResult)
      throw new ForbiddenException({ message: '该视频item不存在!', code: 1 });
      const videoItemUserResult = await this.videoItemUser.findOne({
      where: { videoItemId, userId },
    });
    if (videoItemUserResult) {
      await this.videoItemUser.update(videoItemUserResult.id, {
        videoItemId,
        historyRecord,
        videoId,
        updated_time: new Date(),
      });
      return [];
    } else {
      try {
        await this.videoItemUser.save({
          videoItemId,
          historyRecord,
          userId,
          videoId,
          create_time: new Date(),
          updated_time: new Date(),
        });
        return [];
      } catch (e) {
        console.log('error:', e);
        throw new ForbiddenException({
          message: '添加视频历史记录失败!',
          code: 1,
        });
      }
    }
  }

  //  添加历史记录
  deleteHistory(params) {
    if (!params.id)
      throw new ForbiddenException({
        message: '视频历史id不存在!',
        code: 1,
      });
    try {
      this.videoItemUser.delete({ id: params.id });
      return [];
    } catch (e) {
      console.log('error', e);
      throw new ForbiddenException({
        message: '删除历史记录失败!',
        code: 1,
      });
    }
  }
}
